package com.cjx.minio.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

/**
 *@Author cjunxian
 * @version 1.0.0
 * @date 2020/10/21 10:24:14
 * @doc FFmpeg媒体处理类
 */
public class FFmpegUtil {
  private FFmpegUtil() {
    throw new IllegalStateException("Utility class");
  }

  public static String runCommand(String cmd) {
    try {
      ProcessBuilder pb = new ProcessBuilder(getCommandList(cmd));
      pb.redirectErrorStream(true);
      Process p = pb.start();
      InputStream inStream = p.getInputStream();
      BufferedReader br = new BufferedReader(new InputStreamReader(inStream));
      StringBuilder strBuilder = new StringBuilder();
      String data = null;
      while ((data = br.readLine()) != null) {
        strBuilder.append(data);
      }
      p.waitFor();
      inStream.close();
      br.close();
      return strBuilder.toString();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }

  private static String getFFmpegFilePath() {
    if (System.getProperty("os.name").toLowerCase().startsWith("windows")) {
      return ClassLoader.getSystemResource("ffmpeg").toString().substring(6)
          + File.separator
          + "ffmpeg.exe";
    } else {
      return "ffmpeg";
    }
  }

  private static ArrayList<String> getCommandList(String cmd) {
    ArrayList<String> commandLines = new ArrayList<>();
    commandLines.add(getFFmpegFilePath());
    for (String item : cmd.split(" ")) {
      if (!item.startsWith("ffmpeg")) {
        commandLines.add(item);
      }
    }
    return commandLines;
  }
}
